//simulate chat client

1.times { index ->
	Thread.start("Thread ${index}") {
		Socket socket = new Socket("localhost", 5555)
		def is = socket.getInputStream()
		
		Thread.start {
			println "${Thread.getName()} waiting for message ..."
			StringBuffer msg = new StringBuffer()
			int c
			while ((c = is.read()) != -1) {
				msg.append((char)c)
			}
			println "${Thread.getName()} get '${msg}'"
		}
		
		Thread.start {
			while (true) {
				def msg = "${System.currentTimeMillis()} from ${Thread.getName()}"
				println "send message: ${msg}"
				def os = new BufferedOutputStream(socket.getOutputStream())
				os.write(msg.getBytes())
				os.flush()
				break
//				Thread.sleep((long)(Math.random()*1000))
			}
		}
	}

}
